package leetcode.mthread.h2o;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author scylla
 * @version V1.0
 * @project echo-java-base
 * @title
 * @package leetcode.mthread.h2o
 * @since 2021/12/6 11:12 上午
 */
public class H2oLock {

    private final ReentrantLock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    private volatile int hnums = 0;

    public H2oLock() {

    }

    public void hydrogen(Runnable releaseHydrogen) throws InterruptedException {

        lock.lock();
        try {
            while (hnums == 2) {
                //已有两个氢原子出现，等待氧原子打印
                condition.await();
            }
            // 打印氢原子
            // releaseHydrogen.run() outputs "H". Do not change or remove this line.
            releaseHydrogen.run();

            // 计数加一
            hnums++;

            condition.signalAll();

        } catch (Exception e) {
            System.err.println(Arrays.toString(e.getStackTrace()));
        } finally {
            lock.unlock();
        }


    }

    public void oxygen(Runnable releaseOxygen) throws InterruptedException {

        lock.lock();
        try {
            while (hnums != 2) {
                // 氢原子总数不为 2，阻塞氧原子生成
                condition.await();
            }
            // 打印氧原子
            // releaseOxygen.run() outputs "O". Do not change or remove this line.
            releaseOxygen.run();

            // 重置氢原子计数器
            hnums = 0;

            condition.signalAll();


        } catch (Exception e) {
            System.err.println(Arrays.toString(e.getStackTrace()));
        } finally {
            lock.unlock();
        }

    }

//    /**
//     * 打印者
//     */
//    static class Printer {
//        static void printH() {
//            System.out.println("H");
//        }
//
//        static void printO() {
//            System.out.println("O");
//        }
//    }
}
